<template>
  <div class="ztrust-event-container">
    <!-- 筛选控制区域 -->
    <div class="filter-controls">
      <a-card title="筛选条件" :bordered="false" class="filter-card">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-form-item label="Cybertwin ID">
              <a-input
                v-model:value="filters.cybertwinId"
                placeholder="请输入 Cybertwin ID"
                allow-clear
                @change="applyFilters"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="评级变化">
              <a-select
                v-model:value="filters.scoreType"
                placeholder="选择评级变化类型"
                allow-clear
                @change="applyFilters"
              >
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="INCREASE">上调 (INCREASE)</a-select-option>
                <a-select-option value="REDUCE">下调 (REDUCE)</a-select-option>
                <a-select-option value="CREATE">创建 (CREATE)</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="事件分类">
              <a-select
                v-model:value="filters.eventCategory"
                placeholder="选择事件分类"
                allow-clear
                @change="applyFilters"
              >
                <a-select-option value="">全部</a-select-option>
                <!-- <a-select-option value="access_control">访问控制告警</a-select-option> -->
                <a-select-option value="ddos">DDoS 攻击告警</a-select-option>
                <a-select-option value="microservice">微服务调用链告警</a-select-option>
                <a-select-option value="kernel">内核函数调用链告警</a-select-option>
                <a-select-option value="time_recovery">时间恢复</a-select-option>
                <a-select-option value="legal_recovery">合法操作恢复</a-select-option>
                <a-select-option value="create">创建 Cybertwin</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="时间范围">
              <a-range-picker
                v-model:value="filters.timeRange"
                :format="dateFormat"
                @change="applyFilters"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-statistic
            title="总事件数"
            :value="filteredData.length"
            class="stat-card"
          />
        </a-col>
        <a-col :span="6">
          <a-statistic
            title="评级上调事件"
            :value="increaseEventCount"
            class="stat-card increase-stat"
          />
        </a-col>
        <a-col :span="6">
          <a-statistic
            title="评级下调事件"
            :value="reduceEventCount"
            class="stat-card reduce-stat"
          />
        </a-col>
        <a-col :span="6">
          <a-statistic
            title="今日事件数"
            :value="todayEventCount"
            class="stat-card"
          />
        </a-col>
      </a-row>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <a-table
        :columns="columns"
        :data-source="sortedData"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
        size="middle"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'cybertwin_id'">
            <a-tag color="blue">{{ record.cybertwin_id }}</a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'event'">
            <a-tag :color="getEventTypeColor(record.event)">
              <template v-if="record.event === 'INCREASE'">
                <arrow-up-outlined />
                评级上调
              </template>
              <template v-else-if="record.event === 'REDUCE'">
                <arrow-down-outlined />
                评级下调
              </template>
              <template v-else>
                <plus-outlined />
                创建 Cybertwin
              </template>
            </a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'event_category'">
            <a-tag :color="getEventCategoryColor(record.event_desc)">
              {{ getEventCategoryName(record.event_desc) }}
            </a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'combined_desc'">
            <div class="event-description">
              <div class="event-desc-main">{{ record.event_desc }}</div>
              <div class="score-desc-sub">{{ record.score_desc }}</div>
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'trigger_at'">
            <div class="time-info">
              <div class="time-main">{{ formatDateTime(record.trigger_at) }}</div>
              <div class="time-relative">{{ getRelativeTime(record.trigger_at) }}</div>
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'actions'">
            <a-space>
              <a-button
                type="link"
                @click="viewDetails(record)"
                size="small"
              >
                查看详情
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 详情模态框 -->
    <a-modal
      v-model:open="detailModalVisible"
      title="事件详情"
      :footer="null"
      width="700px"
    >
      <div v-if="selectedRecord">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="事件ID">
            {{ selectedRecord.id }}
          </a-descriptions-item>
          <a-descriptions-item label="Cybertwin ID">
            <a-tag color="blue">{{ selectedRecord.cybertwin_id }}</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="评级变化">
            <a-tag :color="getEventTypeColor(selectedRecord.event)">
              <template v-if="selectedRecord.event === 'INCREASE'">
                <arrow-up-outlined />
                评级上调
              </template>
              <template v-else-if="selectedRecord.event === 'REDUCE'">
                <arrow-down-outlined />
                评级下调
              </template>
              <template v-else>
                <plus-outlined />
                创建 Cybertwin
              </template>
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="事件分类">
            <a-tag :color="getEventCategoryColor(selectedRecord.event_desc)">
              {{ getEventCategoryName(selectedRecord.event_desc) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="触发时间" :span="2">
            <div>
              <div>{{ formatDateTime(selectedRecord.trigger_at) }}</div>
              <div style="color: #666; font-size: 12px; margin-top: 4px;">
                {{ getRelativeTime(selectedRecord.trigger_at) }}
              </div>
            </div>
          </a-descriptions-item>
          <a-descriptions-item label="事件描述" :span="2">
            <div class="detail-description">
              <div class="main-desc">{{ selectedRecord.event_desc }}</div>
              <div class="score-desc">{{ selectedRecord.score_desc }}</div>
            </div>
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, reactive } from 'vue'
import { GetAllZtrustEvents, type ZtrustEvent } from '@/api/ztrust'
import type { TableColumnsType } from 'ant-design-vue'
import { ArrowUpOutlined, ArrowDownOutlined, PlusOutlined } from '@ant-design/icons-vue'
import type { Dayjs } from 'dayjs'

// 响应式数据
const loading = ref(false)
const rawData = ref<ZtrustEvent[]>([])
const detailModalVisible = ref(false)
const selectedRecord = ref<ZtrustEvent | null>(null)
const dateFormat = 'YYYY-MM-DD'

// 筛选条件
const filters = reactive({
  cybertwinId: '',
  scoreType: '',
  eventCategory: '',
  timeRange: null as [Dayjs, Dayjs] | null
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 15,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) => 
    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
})

// 表格列定义
const columns: TableColumnsType<ZtrustEvent> = [
  {
    title: 'Cybertwin ID',
    dataIndex: 'cybertwin_id',
    key: 'cybertwin_id',
    width: 120,
    sorter: true
  },
  {
    title: '评级变化',
    dataIndex: 'event',
    key: 'event',
    width: 120
  },
  {
    title: '事件分类',
    dataIndex: 'event_category',
    key: 'event_category',
    width: 150
  },
  {
    title: '详细描述',
    dataIndex: 'combined_desc',
    key: 'combined_desc',
    width: 350
  },
  {
    title: '触发时间',
    dataIndex: 'trigger_at',
    key: 'trigger_at',
    width: 180,
    sorter: true
  },
  {
    title: '操作',
    dataIndex: 'actions',
    key: 'actions',
    width: 100
  }
]

// 筛选后的数据
const filteredData = computed(() => {
  return rawData.value.filter(item => {
    // Cybertwin ID 筛选
    if (filters.cybertwinId && !item.cybertwin_id.toString().includes(filters.cybertwinId)) {
      return false
    }
    
    // 评级变化筛选
    if (filters.scoreType && item.event !== filters.scoreType) {
      return false
    }
    
    // 事件分类筛选
    if (filters.eventCategory) {
      const category = getEventCategoryKey(item.event_desc)
      if (category !== filters.eventCategory) {
        return false
      }
    }
    
    // 时间范围筛选
    if (filters.timeRange && filters.timeRange.length === 2) {
      const eventTime = new Date(item.trigger_at)
      const startTime = filters.timeRange[0].startOf('day').toDate()
      const endTime = filters.timeRange[1].endOf('day').toDate()
      
      if (eventTime < startTime || eventTime > endTime) {
        return false
      }
    }
    
    return true
  })
})

// 排序后的数据（默认按时间倒序）
const sortedData = computed(() => {
  return [...filteredData.value].sort((a, b) => {
    return new Date(b.trigger_at).getTime() - new Date(a.trigger_at).getTime()
  })
})

// 统计信息计算
const increaseEventCount = computed(() => {
  return filteredData.value.filter(item => item.event === 'INCREASE').length
})

const reduceEventCount = computed(() => {
  return filteredData.value.filter(item => item.event === 'REDUCE').length
})

const todayEventCount = computed(() => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  const tomorrow = new Date(today)
  tomorrow.setDate(tomorrow.getDate() + 1)
  
  return filteredData.value.filter(item => {
    const eventTime = new Date(item.trigger_at)
    return eventTime >= today && eventTime < tomorrow
  }).length
})

// 方法
const fetchData = async () => {
  loading.value = true
  try {
    const res = await GetAllZtrustEvents()
    if (res.code === 0) {
      rawData.value = res.data || []
    }
  } catch (error) {
    console.error('获取信任事件数据失败:', error)
  } finally {
    loading.value = false
  }
}

const applyFilters = () => {
  pagination.current = 1
}

const handleTableChange = (pag: any, filters: any, sorter: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
}

const getEventTypeColor = (eventType: string) => {
  if (eventType === 'INCREASE') return 'green'
  if (eventType === 'REDUCE') return 'red'
  if (eventType === 'CREATE') return 'blue'
  return 'default'
}

const getEventCategoryKey = (eventDesc: string) => {
  if (eventDesc.includes('访问控制告警')) return 'access_control'
  if (eventDesc.includes('DDoS')) return 'ddos'
  if (eventDesc.includes('微服务调用链告警')) return 'microservice'
  if (eventDesc.includes('内核函数调用链告警')) return 'kernel'
  if (eventDesc.includes('基于时间上调')) return 'time_recovery'
  if (eventDesc.includes('基于合法操作上调')) return 'legal_recovery'
  if (eventDesc.includes('创建 Cybertwin') || eventDesc.includes('初始化信任评级')) return 'create'
  return 'other'
}

const getEventCategoryName = (eventDesc: string) => {
  const key = getEventCategoryKey(eventDesc)
  const nameMap: Record<string, string> = {
    access_control: '访问控制告警',
    ddos: 'DDoS 攻击告警',
    microservice: '微服务调用链告警',
    kernel: '内核函数调用链告警',
    time_recovery: '时间恢复',
    legal_recovery: '合法操作恢复',
    create: '创建 Cybertwin',
    other: '其他'
  }
  return nameMap[key] || '其他'
}

const getEventCategoryColor = (eventDesc: string) => {
  const key = getEventCategoryKey(eventDesc)
  const colorMap: Record<string, string> = {
    access_control: 'red',
    ddos: 'volcano',
    microservice: 'orange',
    kernel: 'magenta',
    time_recovery: 'blue',
    legal_recovery: 'green',
    create: 'cyan',
    other: 'default'
  }
  return colorMap[key] || 'default'
}

const formatDateTime = (dateTime: string) => {
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const getRelativeTime = (dateTime: string) => {
  const now = new Date()
  const eventTime = new Date(dateTime)
  const diffMs = now.getTime() - eventTime.getTime()
  const diffMinutes = Math.floor(diffMs / (1000 * 60))
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))

  if (diffMinutes < 1) {
    return '刚刚'
  } else if (diffMinutes < 60) {
    return `${diffMinutes}分钟前`
  } else if (diffHours < 24) {
    return `${diffHours}小时前`
  } else if (diffDays < 7) {
    return `${diffDays}天前`
  } else {
    return '一周前'
  }
}

const viewDetails = (record: ZtrustEvent) => {
  selectedRecord.value = record
  detailModalVisible.value = true
}

// 生命周期
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.ztrust-event-container {
  padding: 24px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.filter-controls {
  margin-bottom: 24px;
}

.filter-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stats-section {
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.increase-stat :deep(.ant-statistic-content) {
  color: #52c41a !important;
}

.reduce-stat :deep(.ant-statistic-content) {
  color: #f5222d !important;
}

.table-section {
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.event-description {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.event-desc-main {
  font-weight: 500;
  color: #333;
}

.score-desc-sub {
  font-size: 12px;
  color: #666;
  font-style: italic;
}

.time-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.time-main {
  font-weight: 500;
  color: #333;
}

.time-relative {
  font-size: 12px;
  color: #666;
}

.detail-description {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.main-desc {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.score-desc {
  font-size: 13px;
  color: #666;
  padding: 8px 12px;
  background-color: #f5f5f5;
  border-radius: 6px;
  border-left: 3px solid #1890ff;
}

/* 表格行悬停效果 */
:deep(.ant-table-tbody > tr:hover > td) {
  background-color: #f5f5f5 !important;
}

/* 统计卡片样式 */
:deep(.ant-statistic-title) {
  color: #666;
  font-size: 14px;
}

:deep(.ant-statistic-content) {
  color: #1890ff;
  font-weight: 600;
}

/* 标签样式 */
:deep(.ant-tag) {
  margin: 0;
  border-radius: 4px;
  font-size: 12px;
}

/* 表单项间距调整 */
:deep(.ant-form-item) {
  margin-bottom: 16px;
}

:deep(.ant-form-item-label) {
  font-weight: 500;
}

/* 日期选择器样式 */
:deep(.ant-picker) {
  width: 100%;
}

/* 事件类型标签特殊颜色 */
.event-type-login {
  background-color: #e6f7ff;
  border-color: #91d5ff;
  color: #1890ff;
}

.event-type-file {
  background-color: #f6ffed;
  border-color: #b7eb8f;
  color: #52c41a;
}

.event-type-network {
  background-color: #fff7e6;
  border-color: #ffd591;
  color: #fa8c16;
}

.event-type-system {
  background-color: #fff2f0;
  border-color: #ffccc7;
  color: #f5222d;
}

.event-type-data {
  background-color: #f9f0ff;
  border-color: #d3adf7;
  color: #722ed1;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .ztrust-event-container {
    padding: 16px;
  }
  
  .filter-controls .ant-col {
    margin-bottom: 16px;
  }
}

@media (max-width: 768px) {
  .event-description {
    gap: 2px;
  }
  
  .time-info {
    gap: 1px;
  }
  
  .stats-section .ant-col {
    margin-bottom: 16px;
  }
  
  .event-desc-main,
  .time-main {
    font-size: 13px;
  }
  
  .score-desc-sub,
  .time-relative {
    font-size: 11px;
  }
}

/* 模态框样式 */
:deep(.ant-modal-content) {
  border-radius: 8px;
}

:deep(.ant-descriptions-item-label) {
  font-weight: 500;
  background-color: #fafafa;
}

/* 箭头图标样式 */
:deep(.anticon-arrow-up) {
  color: #52c41a;
}

:deep(.anticon-arrow-down) {
  color: #f5222d;
}
</style>